/**
 * @Author: easten
 * @Created: 2024-04-15 23:29:48
 * @Description:
 *
 */
import classnames from "classnames";
import React, { useState, useEffect } from "react";
import { RefreshIcon } from "tdesign-icons-react";
import {
  Button,
  MessagePlugin,
  Popconfirm,
  Space,
  Switch,
  Table,
  Tag,
  message,
} from "tdesign-react";
import GatewayDrawer from "./GatewayDrawer";
import { ModuleCommonProps, PageParams } from "_common/DataType";
import { IotGateway } from "_common/entity";
import { ApiGateway } from "_common/api/iot";
import { TableTitle } from "components";
const IotGatewayComp: React.FC<ModuleCommonProps> = (props) => {
  const { axios, className } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([
    1, 2,
  ]);
  const [loading, setLoading] = useState<boolean>(false);
  const [userList, setGatewayList] = useState<IotGateway[]>([]);
  const [selectedRow, setSelectedRow] = useState<IotGateway>();
  const [pageState, setPageState] = useState<PageParams>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
    list: [],
  });

  const [visible, setVisible] = useState(false);
  const [edit, setEdit] = useState(false);
  const apiGateway = new ApiGateway(axios);

  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  useEffect(() => {
    getGatewayList();
  }, [pageState.pageNum, pageState.pageSize]);

  const getGatewayList = async () => {
    setLoading(true);
    const response = await apiGateway.getPage({
      ...pageState,
    });
    if (response && response.code == 200 && response.data) {
      setGatewayList(response.data.list);
      setPageState({
        ...pageState,
        total: response.data.total,
      });
    }
    setLoading(false);
  };

  // 删除用户
  const deleteGateway = async (id: number) => {
    const response = await apiGateway.delete(id);
    if (response && response.code == 200 && response.data) {
      message.success("删除成功");
      getGatewayList();
    }
  };

  return (
    <div className={classnames(className)}>
      <div className="flex flex-row justify-between mb-4">
        <TableTitle text="网关列表" />
        <Space size={5}>
          <Button
            onClick={() => {
              setVisible(true);
              setEdit(false);
            }}
          >
            添加网关
          </Button>
          <Button
            onClick={async () => {
              await apiGateway.restart();
              MessagePlugin?.info("命令已下发！");
            }}
          >
            重启网关
          </Button>
          <Button
            icon={<RefreshIcon />}
            variant="outline"
            onClick={() => {
              getGatewayList();
            }}
          ></Button>
        </Space>
      </div>
      <Table<IotGateway>
        bordered
        columns={[
          {
            align: "left",
            width: 80,
            ellipsis: true,
            colKey: "index",
            title: "序号",
            cell: ({ rowIndex }) => {
              let _index =
                (pageState.pageNum - 1) * pageState.pageSize + rowIndex + 1;
              return <span>{_index}</span>;
            },
          },
          {
            align: "left",
            ellipsis: true,
            colKey: "gatewayName",
            title: "网关名称",
          },
          {
            align: "left",
            ellipsis: true,
            colKey: "gatewayCode",
            title: "网关编码",
          },

          {
            align: "left",
            ellipsis: true,
            colKey: "gatewayDesc",
            title: "网关描述",
          },

          {
            align: "center",
            ellipsis: true,
            colKey: "gatewayType",
            title: "网关类型",
            cell: ({ row }) => {
              return (
                <Tag theme="success" variant="light-outline">
                  {row?.gatewayType == "Tcp" ? "TCP" : "串口"}
                </Tag>
              );
            },
          },
          {
            align: "center",
            ellipsis: true,
            colKey: "enable",
            title: "是否启用",
            width: 150,
            cell: ({ row }) => {
              return (
                <Switch
                  defaultValue
                  value={row.isEnable}
                  onChange={(value) => {
                    apiGateway.enable(row.id, value).then(() => {
                      getGatewayList();
                      MessagePlugin?.info("操作成功！");
                    });
                  }}
                />
              );
            },
          },
          {
            align: "center",
            fixed: "right",
            width: 220,
            colKey: "op",
            title: "操作",
            cell({ row }) {
              return (
                <>
                  <Button
                    theme="success"
                    variant="text"
                    onClick={() => {
                      setVisible(true);
                      setEdit(true);
                      setSelectedRow(row);
                    }}
                  >
                    编辑
                  </Button>
                  <Popconfirm
                    content="确认删除吗"
                    destroyOnClose
                    placement="top"
                    showArrow
                    theme="default"
                    onConfirm={() => deleteGateway(row.id)}
                  >
                    <Button theme="primary" variant="text">
                      删除
                    </Button>
                  </Popconfirm>
                </>
              );
            },
          },
        ]}
        loading={loading}
        data={userList}
        rowKey="index"
        selectedRowKeys={selectedRowKeys}
        verticalAlign="middle"
        hover
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: pageState.pageSize,
          total: pageState.total,
          current: pageState.pageNum,
          showJumper: true,
          onCurrentChange(current) {
            setPageState({
              ...pageState,
              pageNum: current,
            });
          },
          onPageSizeChange(size) {
            setPageState({
              ...pageState,
              pageSize: size,
            });
          },
        }}
      />
      <GatewayDrawer
        axios={axios}
        open={visible}
        edit={edit}
        value={selectedRow}
        onSuccess={() => {
          setVisible(false);
          getGatewayList();
        }}
      />
    </div>
  );
};
export default IotGatewayComp;
